# 用于转换当前目录下的bin文件为c数组文件，并且在同一个头文件下生成数组的申明
import sys
import glob

import os
from os import path


def read_data_from_binary_file(filename, list_data):
    f = open(filename, 'rb')
    f.seek(0, 0)
    while True:
        t_byte = f.read(1)
        if len(t_byte) == 0:
            break
        else:
            list_data.append("0x%.2X" % ord(t_byte))


def write_data_to_text_file(filename, list_data, data_num_per_line):
    length=len(list_data)
    # 在pic_index.h后追加声明
    f_output = open("HMIConfig.h", 'w+')
    f_output.write('extern unsigned char HMIConfig[%d];\n'%length)
    f_output.close()
# 写文件内容到数组
    f_output = open(filename, 'w+')
    f_output.write('#include<HMIConfig.h> \n')
    f_output.write(' unsigned char HMIConfig[%d] = \n'%length)
    f_output.write('{\n    ')
    if ((data_num_per_line <= 0) or data_num_per_line > len(list_data)):
        data_num_per_line = 16
        print('data_num_per_line out of range,use default value\n')
    for i in range(0, len(list_data)):
        if ((i != 0) and(i % data_num_per_line == 0)):
            f_output.write('\n    ')
            f_output.write(list_data[i]+', ')
        elif (i+1) == len(list_data):
            f_output.write(list_data[i])
        else:
            f_output.write(list_data[i]+', ')
    f_output.write('\n};')
    f_output.close()


file_id = 0
list_data = []
data_num_per_line = 16
# 获取当前文件所在的目录
dir = path.dirname(__file__)
print(dir)

# # 删除目录中已经存在的c以及h文件
# dir_str = "%s\\*.c" % dir
# for filename in glob.glob(dir_str):
#     os.remove(filename)
# dir_str = "%s\\*.h" % dir
# for filename in glob.glob(dir_str):
#     os.remove(filename)
# 查找目录下的所有png文件并开始转换 

input_f = "%s\\HMIConfig.bin" % dir
output_f = "%s\\HMIConfig.c" % dir
read_data_from_binary_file(input_f, list_data)
write_data_to_text_file(output_f, list_data, data_num_per_line)
del list_data[:]
 
